<script setup  lang="ts"  name="set_patrol">
import { defineComponent, onMounted, onActivated , reactive, ref, toRaw } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getDeptTree,
  deviceList,
  deviceSave,
  downloadQRCode,
  deviceLog,
  deviceDel,
} from "@/api/server_set_patrol";

const router = useRouter();
const height = ref(0);
const pageSize = ref(20);
const isEdit = ref(false);
const isBig = ref(false);
const tempIndex = ref();
const dialogVisible_add = ref(false);
const dialogVisible_map = ref(false);
const fileList = ref<any[]>([]);
const baseURL = import.meta.env.VITE_RES_URL + '/admin/config/uploadFile';
const formData = ref<any>({
  dept_type:'',
  coordinate:'',
});
const deviceStatusOption = ref<any>({});
const deeptTypeOption = ref<any>({});
const deptOptions = ref([]);
const total = ref(0);
const List = ref([]);
const showDrawer = ref(false);
const showFileDrawer = ref(false);
const deviceLogList = ref<any[]>([]);
const deviceLogTotal = ref(0);
const device_id = ref();
const currentPage = ref(1);
const deviceLogForm = ref({
  page: 1,
  pageSize: 20,
});
const cascaderProps = reactive({
  label: 'label',
  value: 'id',
  children: 'children',
  checkStrictly:true,
  emitPath:false,
})
const statusMap = ref<any>({
  normal:'正常',
  repairing:'维修中',
  broken:'报废',
})

const  activeNames = ref(['collapse0'])

const addItem = () => {
  isEdit.value = false;
  formData.value = {
    dept_type: "inner",
  };
  fileList.value = [];
  dialogVisible_add.value = true;
};

//列表数据
const getList = async (page: number) => {
  let res = await deviceList({
    page: page || 1,
    pageSize: pageSize.value,
  });
  console.log(res)
  if (res.result == "success") {
    List.value = res.list;
    deviceStatusOption.value = res.deviceStatusOption;
    deeptTypeOption.value = res.deptTypeOption;
    total.value = Number(res.total);
  }
};
const getDeptInfo = async () => {
  let res = await getDeptTree({});
  if (res.result == "success") {
    deptOptions.value = res.deptTree;
  }
};
const edit = (data: any) => {
  isEdit.value = true;
  formData.value = {
    ...data,
  };
  let files = data.files ? JSON.parse(data.files) : [];
  fileList.value = files.map((v: any) => {
    return {
      name: v.split("/").reverse()[0],
      url: v,
    };
  });
  dialogVisible_add.value = true;
};
const download = async (data: any) => {
  let res = await downloadQRCode({
    id: data.device_id,
  });
  if (res.result == "success") {
    console.log('二维码',res);
    
    const link = document.createElement("a");
    link.href = 'http://3ssaas.com' + res.pdfUrl;
    link.setAttribute("download",res.pdfUrl);
    document.body.appendChild(link);
    link.click();
  }
};
const record = (data: any) => {
  showDrawer.value = true;
  device_id.value = data.device_id;
  getDeviceLog();
};
const getDeviceLog = async () => {
  let res = await deviceLog({
    id: device_id.value,
    ...deviceLogForm.value,
  });
  if (res.result == "success") {
    deviceLogList.value = res.list;
    deviceLogTotal.value = Number(res.total);
  }
};
const showFiles = (data: any) => {
  formData.value = {
    ...data,
  };
  isEdit.value = true;
  showFileDrawer.value = true;
  let files = data.files ? JSON.parse(data.files) : [];
  fileList.value = files.map((v: any) => {
    return {
      name: v.split("/").reverse()[0],
      url: v,
    };
  });
};
const remove = (data: any) => {
  ElMessageBox.confirm(`<span>确定要删除该设备吗？</span>`, "提 示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    dangerouslyUseHTMLString: true,
    type: "warning",
  }).then(async () => {
    let res = await deviceDel({
      id: data.device_id,
    });
    if (res.result == "success") {
      getList(0);
      ElMessage({
        type: "success",
        message: "删除成功!",
      });
    }
  });
};
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  getList(currentPage.value);
};
const handleCurrentChange = (val: number) => {
  getList(val);
};
const handleCurrentChange2 = (val: number) => {
  deviceLogForm.value.page = val;
  getDeviceLog();
};
const handlePreview = (file: any) => {
   window.open(file.url)
};
const handleRemove = (file: any, fileList: any) => {
   fileList.value = fileList
};
const handleAvatarSuccess = (res: any, file: any, fileList: any) => {
  file.url = res.fileUrl
  fileList.value = fileList
};
const mapClick = (event: any)=>{
    let offsetX = event.offsetX
    let offsetY = event.offsetY
    function setMapIndex(x:number, y:number) {
        let indexPoint:any = document.querySelector('.index-point')
        indexPoint.style.top = `${y}px`
        indexPoint.style.left = `${x}px`
        indexPoint.style.display = `block`
        tempIndex.value = `${x},${y}`
    }
    setMapIndex(offsetX,offsetY)
}
const openMap = ()=> {
  dialogVisible_map.value = true;
  setTimeout(() => {
      setMap()
  },100)
}
const doubleclick = (event: any)=>{
      isBig.value = !isBig.value;
      if(!isBig.value){
          setMap()
          return
      }
      let offsetX = event.offsetX
      let offsetY = event.offsetY
      let mapBlock:any = document.querySelector('.setMapBlock-body')
      let mapId:any = document.querySelector('.setMapBlock')
      let mapBlockHeight = mapBlock.clientHeight
      let mapBlockWidth = mapBlock.clientWidth
      let mapIdHeight = mapId.clientHeight
      let mapIdWidth = mapId.clientWidth
      let left = - event.offsetX + mapBlockWidth/2
      let top = - event.offsetY + mapBlockHeight/2
      setTimeout(() => {
          if(left>0)  left = 0
          if(left< mapBlockWidth-mapIdWidth)  left =  mapBlockWidth-mapIdWidth
          if(top>0)  top = 0
          if(top< mapBlockHeight-mapIdHeight)  top = mapBlockHeight-mapIdHeight
          mapId.style.transform = `scale(${1})`
          mapId.style.left = `${left}px`
          mapId.style.top = `${top}px`
      },100)
      mapId.oncontextmenu = function () {
          return false;
      }

      mapId.addEventListener("mousedown", function(event: any){

          event.stopPropagation();
          var code = event.which;
          if(code != 3  || !isBig.value){
              return
          }
          let left = parseInt(mapId.style.left)
          let top = parseInt(mapId.style.top)
          let ol = event.clientX
          let ot = event.clientY
          document.onmousemove = function(ev){
              let l = left + ev.clientX - ol
              let t =  top + ev.clientY - ot
              if(l>0)  l = 0
              if(l< mapBlockWidth-mapIdWidth)  l = mapBlockWidth-mapIdWidth
              if(t>0)  t = 0
              if(t< mapBlockHeight-mapIdHeight)  t =mapBlockHeight-mapIdHeight
              mapId.style.left =  l + "px";
              mapId.style.top = t + "px";
          }
          document.onmouseup = function(){
              document.onmousemove = null;
          }

      })
  }
const setMap = ()=> {
  let mapBlock:any = document.querySelector('.setMapBlock-body')
  let mapId:any = document.querySelector('.setMapBlock')
  let mapBlockHeight = mapBlock.clientHeight
  let mapBlockWidth = mapBlock.clientWidth
  let mapIdHeight = mapId.clientHeight
  let mapIdWidth = mapId.clientWidth
  let zoomVal = mapBlockHeight / mapIdHeight;
  let left = (mapBlockWidth - mapIdWidth) / 2
  let top = (mapBlockHeight - mapIdHeight) / 2
  mapId.style.transform = `scale(${zoomVal})`
  mapId.style.left = `${left}px`
  mapId.style.top = `${top}px`
  mapId.oncontextmenu = function () {
      return false;
  }
}
const setIndex = ()=>{
   formData.value.coordinate = tempIndex.value
   dialogVisible_map.value = false;
}
const confirmAdd = async (val: number) => {
  //保存数据
  let files = fileList.value.map(v=>{
    if(v.url){
      return v.url
    }
  })
  console.log(formData.device_id)
  let res = await deviceSave({
    ...formData.value,
    id: isEdit.value ? formData.value.device_id : 0,
    deptId:formData.value.dept_id,
    deptType:formData.value.dept_type,
    deptMark:formData.value.dept_mark,
    factoryPhone:formData.value.factory_phone,
    files:files.join(',')
  })
  if(res.result === 'success'){
     ElMessage({
        type: "success",
        message: "保存成功!",
      });
    dialogVisible_add.value = false
      //添加完成后重新获取数据
    getList(0)
  }
};
// 上传图片
const headersObj = ref({
  TOKEN: window.localStorage.getItem("token"),
});
onMounted(() => {
  let pageTable: any = document.querySelector(".page-table");
  height.value = pageTable.clientHeight;
  console.log(height);
  getList(0);
  getDeptInfo();
});
</script>

<template>
  <div class="patrol-page">
    <div class="page-top">
      <h4>巡检配置</h4>
      <el-button type="primary" size="small" @click="addItem"
        >新增设备</el-button
      >
    </div>
    <div class="page-table">
      <el-table ref="table" v-if="height" :data="List" :height="height">
        <el-table-column label="编号" prop="device_id"></el-table-column>
        <el-table-column label="品牌" prop="brand"></el-table-column>
        <el-table-column label="型号" prop="spec"></el-table-column>
        <el-table-column label="位置" prop="coordinate"></el-table-column>
        <el-table-column label="部门" prop="deptName"></el-table-column>
        <el-table-column label="售后" prop="dept_type">
          <template #default="{ row }">
            <span>{{ deeptTypeOption[row.dept_type] }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="厂家联系电话"
          prop="factory_phone"
        ></el-table-column>
        <el-table-column label="状态" prop="status">
          <template #default="{ row }">
            <span class="status_icon" :class="[`${row.status}`]"></span>
            <span>{{ deviceStatusOption[row.status] }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="340">
          <template #default="{ row }">
            <el-button link size="small" @click="edit(row)">编辑</el-button>
            <el-button link size="small" @click="remove(row)">删除</el-button>
            <el-button link size="small" @click="showFiles(row)"
              >查看资料</el-button
            >
            <el-button link size="small" @click="record(row)"
              >报修记录</el-button
            >
            <el-button link size="small" @click="download(row)"
              >下载二维码</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page-pagination">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        v-model:currentPage="currentPage"
        :page-sizes="[20, 50, 80, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>

   <el-dialog :close-on-click-modal="false"  :title="isEdit?'编辑设备':'新增设备'" v-model="dialogVisible_add" width="500px">
    <el-form ref="form" :model="formData" label-width="120px">
      <el-form-item label="设备编号" v-if="isEdit">
        <el-input type="number" disabled placeholder="请输入" v-model="formData.device_id"></el-input>
      </el-form-item>
      <el-form-item label="品牌名字">
        <el-input type="text" placeholder="请输入" v-model="formData.brand"></el-input>
      </el-form-item>
      <el-form-item label="型号">
        <el-input type="text" placeholder="请输入" v-model="formData.spec"></el-input>
      </el-form-item>
      <el-form-item label="地图坐标" >
              <div class="btn-act">
               <el-input class="btn-input" type="text" placeholder="坐标" disabled
                          v-model="formData.coordinate"></el-input>
                          <el-button class="btn" @click="openMap()" type="primary" plain
                  >设置位置</el-button
                >
              </div>
            </el-form-item>
      <el-form-item label="部门">
        <el-cascader style="width:100%" :props="cascaderProps" v-model="formData.dept_id" :options="deptOptions" clearable>
        </el-cascader>
      </el-form-item>
      <el-form-item label="售后">
        <el-radio-group v-model="formData.dept_type">
          <el-radio :label="key" :key="key" v-for="(item,key) in deeptTypeOption">{{item}}</el-radio>
        </el-radio-group>
        <el-input type="text" placeholder="请输入售后备注" v-model="formData.dept_mark"></el-input>
      </el-form-item>
      <el-form-item label="厂家联系电话">
        <el-input type="text" placeholder="请输入" v-model="formData.factory_phone"></el-input>
      </el-form-item>
      <el-form-item label="设备资料上传">
        <el-upload
                class="upload-demo"
                name="uploadFile" :headers="headersObj"
                :action="baseURL"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :on-success="handleAvatarSuccess"
                multiple
                :file-list="fileList">
          <el-button size="small" type="primary">点击上传</el-button>
          <template #tip>
              <div  class="el-upload__tip">支持扩展名：.rar .zip .doc .docx .pdf .jpg...</div>
          </template>

        </el-upload>
      </el-form-item>


    </el-form>
    <el-dialog :close-on-click-modal="false"  title="提示" :destroy-on-close="true" v-model="dialogVisible_map" width="800">
        <div class="setMapBlock-body">
            <div id="rightClickDiv">
                <div class="addProductSpan liHover">选择位置</div>
            </div>
            <div class="setMapBlock" @dblclick="doubleclick"  @click="mapClick">
                <img src="@/assets/image/home/map.png" />
                <div class="index-point" style="top:1px;left:1px">
                    <img src="@/assets/image/home/shebei1.png">
                </div>
            </div>
        </div>
        <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible_map = false">取 消</el-button>
          <el-button type="primary" @click="setIndex()">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <template #footer>
        <el-button @click="dialogVisible_add = false">取 消</el-button>
        <el-button type="primary" @click="confirmAdd">确 定</el-button>
   </template>
  </el-dialog>
    <el-drawer
          title="查看资料"
          size="400px"
          v-model="showFileDrawer"
          direction="rtl">
    <div class="drawer-block">
      <el-upload
              class="upload-demo"
              name="uploadFile"
              drag
              :action="baseURL" :headers="headersObj"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="handleAvatarSuccess"
              multiple
              :file-list="fileList">
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div  class="el-upload__tip">支持扩展名：.rar .zip .doc .docx .pdf .jpg...</div>
        </template>
      </el-upload>
      <div>
        <el-button style="float:right;" size="small" type="primary" @click="confirmAdd">保存</el-button>
      </div>
    </div>

  </el-drawer>

  <el-drawer
          title="报修记录"
          size="560px"
          v-model="showDrawer"
          direction="rtl">
    <div class="drawer-block">
      <el-collapse v-model="activeNames">
        <el-collapse-item  :name="`collapse${index}`" :key="index" v-for="(item,index) in deviceLogList">
          <template #title>
            <span class="bx-status" :class="[item.status]">{{statusMap[item.status]}}</span>
            <h3>第{{item.report_cnt}}次报修 {{item.gmt_create}}</h3>
          </template>
          <div>
            <div>巡检员：{{item.reportName}}</div>
            <div>上传图片</div>
            <div class="image_list">
              <el-image
                      fit="contain"
                      :key="i" v-for="(image,i) in item.report_images"
                      class="image-item"
                      :src="image"
                      :preview-src-list="item.report_images">
              </el-image>
            </div>
            <div>备注：{{item.report_mark}}</div>
          </div>
          <div>
            <h3>售后时间：{{item.gmt_modified}}</h3>
            <div>售后员：{{item.repairName}}</div>
            <div>上传图片</div>
            <div class="image_list">
              <el-image
                      fit="contain"
                      :key="i" v-for="(image,i) in item.repair_images"
                      class="image-item"
                      :src="image"
                      :preview-src-list="item.repair_images">
              </el-image>

            </div>
            <div>备注：{{item.repair_mark}}</div>
          </div>
        </el-collapse-item>
      </el-collapse>
    </div>
    <el-pagination  layout="prev, pager, next" :page-size="deviceLogForm.pageSize"
                    @current-change="handleCurrentChange2" :current-page="deviceLogForm.page" :total="deviceLogTotal">
    </el-pagination>
  </el-drawer>

  </div>
</template>

<style lang="scss">
.patrol-page {
  width: 100%;
  height: 100%;
  .page-top {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .page-table {
    margin: 16px 0;
    height: calc(100% - 100px);
  }
  .status_icon{
   width:10px;
   height:10px;
   border-radius: 10px;
   display: inline-block;
   vertical-align: middle;
   position:relative;
   bottom:2px;
}
.normal{
    background: #2FCC95;
}
.broken{
    background: red;
}
.repairing{
    background: #FF7300;
}
.bx-status{
    padding: 5px;
    border-radius: 5px;
    display: inline-block;
    vertical-align: middle;
    line-height: 16px;
    color: #fff;
    font-size:12px;
    margin-right: 10px;
}


.el-drawer__header{
    margin-bottom: 10px;
}
.drawer-block{
    padding: 0 20px;
    height: calc(100% - 40px);
    overflow: auto;
}

.image_list{
    display:flex;
    flex-wrap: wrap;
}
.image_list .image-item{
    width: 80px;
    height: 80px;
    border: 1px dashed #ccc;
    margin:9px ;
}


.el-collapse {
    border: none !important;
}
.el-collapse-item{
    margin-bottom: 10px;
    text-align:left;
}
.el-collapse-item__content{
    background: rgba(255, 255, 255, 0.03);
    border-radius: 4px;
    border: 1px solid #F0F0F0;
    padding:0 10px
}
.el-collapse-item__wrap{
    border: none !important;
}
.el-collapse-item__header{
    background: #222121;
    border-radius: 5px;
    border-bottom:unset;
    padding-left: 10px;
}
}
.setMapBlock-body {
  width: 100%;
  height: 500px;
  overflow: hidden !important;
  position: relative;
  border: 1px solid #000;
}
.setMapBlock {
  display: inline-block;
  position: absolute;
  cursor: pointer;
}
.setMapBlock .index-point {
  width: 0;
  height: 0;
  position: absolute;
  display: none;
}
.setMapBlock .index-point img {
  position: absolute;
  width: 144px;
  left: -144px;
  bottom: 0;
}
.btn-act {
  display: flex;
  .btn-input {
    width: 100px;
  }
}
.btn {
  margin-left: 15px;
}
</style>
